/*********************************************************************************
 *      Copyright:  (C) 2022 South-Central Minzu University
 *                  All rights reserved.
 *
 *       Filename:  server.c
 *    Description:  This file Raspberry pie timing access temperature server
 *                 
 *        Version:  1.0.0(23/04/22)
 *         Author:  zhangkang <2980640573@qq.com>
 *      ChangeLog:  1, Release initial version on "23/04/22 16:33:16"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <signal.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h> 
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>

#include "logger.h"
#include "sqlite3.h"

#define MAX_EVENTS 512
#define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0]))



static inline void print_usage(char *progname);
void sig_handle(int signum);


int                       g_sigstop=0; 

int main(int argc, char **argv)
{
    char                      db_name[16]="temp_ser.db";
    struct epoll_event        event_array[MAX_EVENTS];
    struct epoll_event        event;
    struct sigaction          sigign;
    char                     *progname = NULL;
    char                     *p= NULL;
    char                     *buf_data[3];
    char                      buf_id[16];
    char                      buf[1024];
    int                       daemon_run = 0;
    int                       serv_port = 0;
    int                       listenfd,connfd;
    int                       i, j;
    int                       epollfd;
    int                       events;  
    int                       found; 
    int                       opt;
    int                       t=0;
    int                       rv;                     
    struct option long_options[] ={ 
                                      {"daemon", no_argument, NULL, 'b'},
                                      {"port", required_argument, NULL, 'p'},
                                      {"help", no_argument, NULL, 'h'},
                                      {NULL, 0, NULL, 0}
                                  }; progname = basename(argv[0]);
 
    
                       
    while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1)
    { 
        switch (opt)
        { 
            case 'b':
                    daemon_run=1;
                    break;
            case 'p':
                    serv_port = atoi(optarg);
                    break;
            case 'h': 
                    print_usage(progname);
                    return EXIT_SUCCESS;
                    default:
                    break;
        } 
    } 
    
    if( !serv_port )
    { 
        print_usage(progname);
        return -1;
    }

                       /*zlog*/
     if( logger_init("stdout", LOG_LEVEL_DEBUG) < 0)
    {
        fprintf(stderr, "initial logger system failure\n");
        return 1;
    }
 
          /*signal*/
    signal(SIGINT,sig_handle);
    signal(SIGTERM,sig_handle);
      
         /*sqlite init*/
   if( ( sqlite_init(db_name) ) < 0  )
   {
       log_warn("sqlite initialization failed\n");
   }
   else
   {
       log_info("sqlite initialization scuessfully\n");
   }
       
    set_socket_rlimit(); 
    
                    
    if( (listenfd=socket_server_init(NULL, serv_port)) < 0 )
    {
        log_error("ERROR: %s server listen on port %d failure\n", argv[0],serv_port);
        return -2;
    }
    printf("%s server start to listen on port %d\n", argv[0],serv_port);

                       /*daemon*/
    if(daemon_run)
	  {
		    if(daemon(0, 0))
		    {
			     log_error("Running daemon failure:%s\n", strerror(errno));
		    }
		    log_info("Running daemon successfully!\n");
	  }
    
    if( (epollfd=epoll_create(MAX_EVENTS)) < 0 )
    {
        log_error("epoll_create() failure: %s\n", strerror(errno));
        return -3;
    }

    event.events = EPOLLIN;
    event.data.fd = listenfd;
    if( epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event) < 0)
    {
        log_error("epoll add listen socket failure: %s\n", strerror(errno));
        return -4;
    }
    
    while(  !g_sigstop )
    {    
        events = epoll_wait(epollfd, event_array, MAX_EVENTS, -1);
        if(events < 0)
        {
            log_error("epoll failure: %s\n", strerror(errno));
            break;
        }
        else if(events == 0)
        {
            log_warn("epoll get timeout\n");
            continue;
        }
 
        for(i=0; i<events; i++)
        {
            if ( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) )
            {
                log_error("epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno));
                epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                close(event_array[i].data.fd);
            }
 
            if( event_array[i].data.fd == listenfd )
            {
                if( (connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0)
                {
                    log_error("accept new client failure: %s\n", strerror(errno));
                    continue;
                }
                event.data.fd = connfd;
 
                event.events = EPOLLIN;
                if( epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &event) < 0 )
                {
                    log_error("epoll add client socket failure: %s\n", strerror(errno));
                    close(event_array[i].data.fd);
                    continue;
                }
                log_info("epoll add new client socket[%d] ok.\n", connfd);
            }
            else 
            {
                if( (rv=read(event_array[i].data.fd, buf, sizeof(buf))) <= 0)
                {
                    log_error("socket[%d] read failure or get disconncet and will be removed.\n",event_array[i].data.fd);
                    epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                    close(event_array[i].data.fd);
                    continue;
                }
                else
                {
                    log_info("socket[%d] read get %d bytes data\n", event_array[i].data.fd, rv);
                    log_info("The data from client is : %s\n",buf);
    
                    p = strtok(buf, "/");
	                  while(p)
                    {
                        buf_data[t]=p;
                        t=t+1;
                        p = strtok(NULL, "/");
                    }
    
                   log_info("A:%s,B:%s,C:%s\n",buf_data[0],buf_data[1],buf_data[2]);
                   sqlite_insert_data(buf_data);
                    
                }
            }
        }
    }
    sqlite_close_db();
    log_warn("I QUIT GRACEFULLY\n"); 
    logger_term();
       
    CleanUp:
    close(listenfd);
    return 0;
}

static inline void print_usage(char *progname)
{
    printf("Usage: %s [OPTION]...\n", progname);
    printf(" %s is a socket server program, which used to verify client and echo back string from it\n",progname);
    printf("\nMandatory arguments to long options are mandatory for short options too:\n");
    printf(" -b[daemon ] set program running on background\n");
    printf(" -p[port ] Socket server port address\n");
    printf(" -h[help ] Display this help information\n");
    printf("\nExample: %s -b -p 8900\n", progname);
    return ;
}

void sig_handle(int signum)               //安装信号
{
    log_warn("catch signal [%d]\n",signum);
    g_sigstop = 1;
}
